package cn.sciento.iam.saas.api.controller.v1;


import cn.sciento.core.iam.ResourceLevel;
import cn.sciento.swagger.annotation.Permission;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import cn.sciento.core.base.BaseController;
import cn.sciento.core.util.Results;
import cn.sciento.iam.domain.entity.Tenant;
import cn.sciento.iam.domain.repository.TenantRepository;
import cn.sciento.iam.saas.app.service.TenantService;
import cn.sciento.mybatis.domian.SecurityToken;
import cn.sciento.mybatis.helper.SecurityTokenHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = {"Tenant(Site Level)"})
@RestController("tenantManageController.v1")
@RequestMapping({"/v1/tenants"})
public class TenantManageController extends BaseController {
  @Autowired
  private TenantRepository tenantRepository;
  
  @Autowired
  private TenantService tenantService;
  
  @ApiOperation("根据租户ID查询租户信息")
  @Permission(level = ResourceLevel.SITE)
  @GetMapping({"/{tenantId}"})
  public ResponseEntity<Tenant> selectTenant(@ApiParam(value = "租户ID", required = true) @PathVariable Long tenantId) {
    return Results.success(this.tenantRepository.selectTenantDetails(tenantId));
  }
  
  @Permission(level = ResourceLevel.SITE)
  @ApiOperation("创建租户")
  @PostMapping
  public ResponseEntity<Tenant> create(@RequestBody Tenant tenant) {
    return Results.success(this.tenantService.createTenant(tenant));
  }
  
  @Permission(level = ResourceLevel.SITE)
  @ApiOperation("更新租户")
  @PutMapping({"/{tenantId}"})
  public ResponseEntity<Tenant> update(@ApiParam(value = "租户ID", required = true) @PathVariable(name = "tenantId") Long tenantId, @RequestBody Tenant tenant) {
    validObject(tenant);
    SecurityTokenHelper.validToken(tenant);
    return Results.success(this.tenantService.updateTenant(tenant.getTenantId(), tenant));
  }
  
  @Permission(level = ResourceLevel.SITE)
  @ApiOperation("用户分配租户")
  @PostMapping({"/assign-to-user"})
  public ResponseEntity<Integer> assignTenantToUser(@ApiParam(value = "租户Id", required = true) @RequestParam Long tenantId, @ApiParam(value = "用户ID", required = true) @RequestParam Long userId) {
    return Results.success(this.tenantService.assignTenantToUser(tenantId, userId));
  }
}
